import { createWebHistory, createRouter } from 'vue-router'
import NotFound from '@/views/error/NotFound.vue'
import Welcome from "@/views/welcome/Index.vue";
import Login from "@/views/login/Index.vue";
import Main from '../views/layout/Main.vue';

import ProductList from "@/views/product/List.vue";
import SkuList from "@/views/sku/List.vue";

const routes = [
  {
    path: '/',
    component: Main,
    redirect: '/welcome',
    children: [
      { path: 'welcome', name: 'welcome', component: Welcome },
      { path: 'productlist', name: 'productlist', component: ProductList },
      { path: 'skulist', name: 'skulist', component: SkuList }
    ]
  },
  { path: '/login', component: Login },
  { path: '/:pathMatch(.*)*', component: NotFound }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫优化
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem("author_token");
  
  // 明确放行登录页
  if (to.path === '/login') {
    return next();
  }

  // 检查token
  if (!token) {
    return next('/login');
  }

  next();
});

export default router;